from tornado import gen
from base.BaseHandler import AuthHandler
from base.DateHandler import DateHandler
from base.Models import UserDoLog


class UserDoLogHandler(AuthHandler):
    @gen.coroutine
    def get(self):
        result = self.result()
        try:
            data = self.get_params()
            page = int(data.get("page", 1))
            limit = int(data.get("limit", 10))
            key_word = data.get("key_word")
            date_time = data.get("date_time")
            data_list = []

            log_objects = self.session.query(UserDoLog).filter_by(user_id=self.user_id)

            if key_word:
                log_objects = log_objects.filter(UserDoLog.todo.like(f"%{key_word}%"))
            company_data = log_objects.order_by(UserDoLog.create_time.desc())\
                                      .limit(limit).offset((page - 1) * limit).all()
            for raw in company_data:
                arr = {
                    "id": raw.id,
                    "user_name": raw.user_name,
                    "todo": raw.todo,
                    "ip": raw.ip,
                    "create_time": str(raw.create_time)
                }
                data_list.append(arr)
            data = {
                "data_count": log_objects.count(),
                "data_list": data_list
            }
            result["status"] = 1
            result["msg"] = "数据获取成功！"
            result["data"] = data
        except Exception as e:
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

